//
//  FreePaiViewController.m
//  XDBaseFrameWork
//
//  Created by boyima on 14-10-27.
//  Copyright (c) 2014年 XD-XY. All rights reserved.
//

#import "FreePaiViewController.h"
#import "CameraManCell.h"

#import "ShowRecommendWebViewController.h"

@interface FreePaiViewController ()
{
    UIWebView * malongWeb;
    UIButton * downBtn;
}
@end

@implementation FreePaiViewController

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [mapView viewWillDisappear];
    mapView.delegate = nil;
    [locService stopUserLocationService];
    locService.delegate = nil;
    searcher.delegate = nil;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    [mapView viewWillAppear];
    mapView.delegate = self;
    locService.delegate = self;
    searcher.delegate  = self;
    [locService startUserLocationService];
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if (![[NSUserDefaults standardUserDefaults] valueForKey:@"suiyipairecommand"]){
        [self performSelector:@selector(showRecommand) withObject:nil afterDelay:0.5];

    }
}


-(void)backPrePage
{
//    [locService stopUserLocationService];
    mapView.showsUserLocation = NO;
    mapView.delegate = nil;
    locService.delegate = nil;
    searcher.delegate = nil;
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    

    self.titleLabel.text = @"随e拍";
    
    dataArray = [[NSMutableArray alloc] init];
    currentPage = 1;
    
    float h = 0;
    if (IOS7) {
        h = 20;
    }
    
    changeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [changeBtn setFrame:CGRectMake(UI_SCREEN_WIDTH-50, h, 50, UI_NAVIGATION_BAR_HEIGHT)];
    [changeBtn setBackgroundImage:LOADIMAGE(@"list@2x") forState:UIControlStateNormal];
    [changeBtn setBackgroundImage:LOADIMAGE(@"map@2x") forState:UIControlStateSelected];
    [changeBtn addTarget:self action:@selector(changeMapAndList) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationBarView addSubview:changeBtn];
    
    UIButton * helpBtn = [self createButtonOnNavigationWithRect:CGRectMake(changeBtn.frame.origin.x-50, 0, 50, 44) normalImg:LOADIMAGE(@"i3@2x") highlightImg:LOADIMAGE(@"i3@2x")];
    [helpBtn addTarget:self action:@selector(showRecommand) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationBarView addSubview:helpBtn];
    
    myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, UI_MAINSCREEN_HEIGHT-UI_NAVIGATION_BAR_HEIGHT) style:UITableViewStylePlain];
    myTableView.dataSource = self;
    myTableView.delegate = self;
    myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    myTableView.backgroundColor = [UIColor clearColor];
    myTableView.hidden = YES;
    [self.contentView addSubview:myTableView];
    
    mapView = [[BMKMapView alloc] initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, UI_MAINSCREEN_HEIGHT-2*UI_NAVIGATION_BAR_HEIGHT)];
    [mapView setZoomLevel:17];
    [self.contentView addSubview:mapView];
    
    
    searcher = [[BMKGeoCodeSearch alloc]init];
    searcher.delegate = self;
    
    locService = [[BMKLocationService alloc] init];
    locService.delegate  =self;
    [locService startUserLocationService];

    footView = [UIView initViewRect:CGRectMake(0, UI_MAINSCREEN_HEIGHT-2*UI_NAVIGATION_BAR_HEIGHT - 5, UI_SCREEN_WIDTH, UI_NAVIGATION_BAR_HEIGHT) andBackGroudColor:[UIColor whiteColor]];
    [self.contentView addSubview:footView];

    // 加一条线
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, 0.5)];
    lineView.backgroundColor = [UIColor lightGrayColor];
    lineView.alpha = 0.7;
    [footView addSubview:lineView];

    addressLB = [UILabel initLabelText:nil andRect:CGRectMake(10, 5, 300, 35) andBackGroudColor:mClearColor andTextFont:[UIFont systemFontOfSize:13] andTextColor:UIColorFromRGB(0x666666) andTextAlignment:NSTextAlignmentLeft];
    // 可以换行
    addressLB.numberOfLines = 0;
//    [footView addSubview:addressLB];
    
    UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, UI_NAVIGATION_BAR_HEIGHT)];
    [btn setBackgroundColor:[UIColor clearColor]];
    [btn addTarget:self action:@selector(chooseAddress) forControlEvents:UIControlEventTouchUpInside];
//    [footView addSubview:btn];
    
    UIImage * image = LOADIMAGE(@"surexiadanbtn@2x");
    [image resizableImageWithCapInsets:UIEdgeInsetsMake(8, 8, 8, 8)];
    
    UIButton * yuyueBtn = [UIButton initButton:CGRectMake((UI_SCREEN_WIDTH-200)/2,7, 200,35) btnImage:image btnTitle:@"我要预约" titleColor:[UIColor whiteColor] titleFont:[UIFont systemFontOfSize:16]];
    [yuyueBtn addTarget:self action:@selector(changeMapAndList) forControlEvents:UIControlEventTouchUpInside];
    [footView addSubview:yuyueBtn];
    
    
    
    if ([XDTools sharedXDTools].longitude&&[XDTools sharedXDTools].latitude){
        NSDictionary * dict = @{@"Lat": [NSString stringWithFormat:@"%f",[XDTools sharedXDTools].latitude],
                                @"Lng": [NSString stringWithFormat:@"%f",[XDTools sharedXDTools].longitude]};
        [XDTools showProgress:self.contentView];
        [self getDataWithDict:dict api:API_FREEPAILIST];
    }else{
        [XDTools showTips:@"请在隐私中打开定位服务" toView:self.view];
    }

    [self getDingWeiInfo];
    
    malongWeb = [[UIWebView alloc] init];
    malongWeb.frame = CGRectMake(0, self.view.frame.size.height,self.view.frame.size.width, self.view.frame.size.height);
    malongWeb.backgroundColor = mClearColor;
    NSString * s = @"http://www.meike365.cn/index.php?m=Api&c=Index&a=suie";
    [malongWeb loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:s]]];
    malongWeb.hidden = YES;
    malongWeb.delegate = self;
    malongWeb.scrollView.delegate = self;
    
    [self.view addSubview:malongWeb];
    
    CGFloat dheight = IOS7?20:0;
    downBtn = [UIButton initButton:CGRectMake(UI_SCREEN_WIDTH-42, dheight+20,32,32) btnImage:LOADIMAGE(@"wcha@2x") btnTitle:nil];
    [downBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    downBtn.backgroundColor = [UIColor clearColor];
    [downBtn addTarget:self action:@selector(downRecommend) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:downBtn];
    downBtn.hidden = YES;
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    DDLOG(@"height = %f   y = %f",malongWeb.scrollView.contentSize.height,malongWeb.scrollView.contentOffset.y);
    if (scrollView == malongWeb.scrollView){
        if(malongWeb.scrollView.contentSize.height-malongWeb.scrollView.contentOffset.y<UI_SCREEN_HEIGHT-150){
            [self downRecommend];
        }
    }
    
}

-(void)showRecommand
{
    malongWeb.hidden = NO;
    [UIView animateWithDuration:0.45 animations:^{
        malongWeb.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    } completion:^(BOOL finished) {
        downBtn.hidden = NO;
    }];
}

-(void)downRecommend
{
    downBtn.hidden = YES;
    [UIView animateWithDuration:0.45 animations:^{
        malongWeb.frame = CGRectMake(0,self.view.frame.size.height, self.view.frame.size.width, self.view.frame.size.height);
    } completion:^(BOOL finished) {
        malongWeb.hidden = NO;
    }];
    [[NSUserDefaults standardUserDefaults] setValue:@"1" forKey:@"suiyipairecommand"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)changeMapAndList{
    if (!mapView.hidden) {
        myTableView.hidden = NO;
        mapView.hidden = YES;
        changeBtn.selected = YES;
        footView.hidden = YES;
    }else{
        myTableView.hidden = YES;
        mapView.hidden = NO;
        changeBtn.selected = NO;
        footView.hidden = NO;
    }
}


-(void)getDataWithDict:(NSDictionary *)dict api:(NSString *)api
{
    if (![XDTools NetworkReachable]) {
        [XDTools hideProgress:self.contentView];
        [XDTools showTips:brokenNetwork toView:self.contentView];
        return;
    }
    
    __weak ASIHTTPRequest *request = [XDTools postRequestWithDict:dict API:api];
    [request setCompletionBlock:^{
        [XDTools hideProgress:self.contentView];
        
        NSDictionary *tempDic = [XDTools  JSonFromString:[request responseString]];
        
        if([[tempDic objectForKey:@"status"]intValue] == 1){
            
            DDLOG(@"dic = %@",tempDic);
            
            totalCount = [tempDic[@"data"][@"Count"] intValue];
            
            if (currentPage == 1) {
                dataArray = [NSMutableArray arrayWithArray:tempDic[@"data"][@"List"]];
            }else{
                [dataArray addObjectsFromArray:tempDic[@"data"][@"List"]];
            }
            
            if (dataArray.count == totalCount) {
                totalCount = -999;
            }
            dataArray = [self rank:dataArray];

            [myTableView reloadData];
            
            [self reloadMapViews];

        }else{
            [XDTools showTips:tempDic[@"msg"] toView:self.view];
            
        }
    }];
    
    [request setFailedBlock:^{
        [XDTools hideProgress:self.contentView];
    }];
    [request startAsynchronous];
    [XDTools showProgress:self.contentView];
}


#pragma mark - UITableView Datasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 80;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString * cellIde = @"cell";
    CameraManCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIde];
    if (!cell) {
        cell = [[CameraManCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIde];
        cell.backgroundColor = [UIColor whiteColor];
    }
    
    NSDictionary *dict = dataArray[indexPath.row];

    [cell initFreePaiViewsWithDict:dict];
    
    return cell;
}

// 在这里排序
- (NSMutableArray *)rank:(NSMutableArray *)dictSort
{
    NSArray *sortedArray = [dictSort sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2){

        if ([obj1[@"Range"] doubleValue] > [obj2[@"Range"] doubleValue]){
            
            return NSOrderedDescending;
        } 
        
        if ([obj1[@"Range"] doubleValue] < [obj2[@"Range"] doubleValue]){
            
            return NSOrderedAscending;
        } 
        
        return NSOrderedSame; 
        
    }];

    dictSort = [NSMutableArray arrayWithArray:sortedArray];
    return dictSort;
}

#pragma mark - UITableView Delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    CameraManDetailViewController * cameraMan = [[CameraManDetailViewController alloc] init];
    cameraMan.cameraManID = dataArray[indexPath.row][@"EmplID"];
    //        cameraMan.type = _type;
    if ([dataArray[indexPath.row][@"IsAuthen"] intValue]) {
        cameraMan.isRenZheng = YES;
    }else{
        cameraMan.isRenZheng = NO;
    }
    cameraMan.distance = dataArray[indexPath.row][@"Range"];
    [self.navigationController pushViewController:cameraMan animated:YES];
    
}

- (void)reloadMapViews{
    for (int i = 0; i < dataArray.count; i++) {
        NSDictionary * dict = dataArray[i];
        BMKPointAnnotation* item = [[BMKPointAnnotation alloc]init];
        CLLocationCoordinate2D loc = CLLocationCoordinate2DMake([dict[@"CurN"] floatValue], [dict[@"CurE"] floatValue]);
        item.coordinate = loc;
        item.title = @"man";
        [mapView addAnnotation:item];
        
        
        //            mapView.centerCoordinate = result.location;
        
    }
}


- (void)mapView:(BMKMapView *)mapView didSelectAnnotationView:(BMKAnnotationView *)view{
    
}



#pragma mark
#pragma mark 定位
-(void)getDingWeiInfo
{
    if([XDTools sharedXDTools].latitude&&[XDTools sharedXDTools].longitude){
        [locService startUserLocationService];
        mapView.showsUserLocation = NO;//先关闭显示的定位图层
        mapView.userTrackingMode = BMKUserTrackingModeNone;//设置定位的状态
        mapView.showsUserLocation = YES;//显示定位图层
        
        
//        circle = [BMKCircle circleWithCenterCoordinate:CLLocationCoordinate2DMake([XDTools sharedXDTools].latitude,[XDTools sharedXDTools].longitude) radius:5000];
//        [mapView addOverlay:circle];
        
    }else{
        [XDTools showTips:@"请在隐私中打开定位服务" toView:self.view];
    }
}

#pragma mark
#pragma mark 地图定位+显示
/**
 *在地图View将要启动定位时，会调用此函数
 *@param mapView 地图View
 */
-(void)willStartLocatingUser
{
    DDLOG(@"开始定位!!!!!!!!!!!!!!!!!!!!!!!!!");
}

-(void)didStopLocatingUser
{
    DDLOG(@"停止定位!!!!!!!!!!!!!!!!!!!!!!!!!");
}

/**
 *用户方向更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
    latitude = userLocation.location.coordinate.latitude;
    longitude = userLocation.location.coordinate.longitude;
    if (latitude&&longitude){
        [locService stopUserLocationService];
        [mapView updateLocationData:userLocation];
        
        [XDTools sharedXDTools].latitude = latitude;    //经度
        [XDTools sharedXDTools].longitude = longitude;  //纬度
    }
    
}

/**
 *用户位置更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateUserLocation:(BMKUserLocation *)userLocation
{
    latitude = userLocation.location.coordinate.latitude;
    longitude = userLocation.location.coordinate.longitude;
    if (latitude&&longitude){
        [locService stopUserLocationService];
        [mapView updateLocationData:userLocation];
        
        [XDTools sharedXDTools].latitude = latitude;    //经度
        [XDTools sharedXDTools].longitude = longitude;  //纬度
        
        [mapView setCenterCoordinate:userLocation.location.coordinate animated:YES];
        
        //发起反向地理编码检索
        BMKReverseGeoCodeOption *reverseGeoCodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
        reverseGeoCodeSearchOption.reverseGeoPoint = userLocation.location.coordinate;
        BOOL flag = [searcher reverseGeoCode:reverseGeoCodeSearchOption];
        if(flag)
        {
            NSLog(@"反geo检索发送成功");
        }
        else
        {
            NSLog(@"反geo检索发送失败");
        }
    }
}


/**
 *定位失败后，会调用此函数
 *@param mapView 地图View
 *@param error 错误号，参考CLError.h中定义的错误号
 */
- (void)didFailToLocateUserWithError:(NSError *)error
{
    DDLOG(@"error = %@",error);
}



//接收反向地理编码结果
-(void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result
                        errorCode:(BMKSearchErrorCode)error{
    if (error == BMK_SEARCH_NO_ERROR) {
        //在此处理正常结果


        NSString *str = [NSString stringWithFormat:@"拍摄地点:%@",result.address];
        addressLB.text = str;
        
    }
    else {
        NSLog(@"抱歉，未找到结果");
    }
}


#pragma mark
#pragma mark 根据anntation生成对应的View
- (BMKAnnotationView *)mapView:(BMKMapView *)view viewForAnnotation:(id <BMKAnnotation>)annotation
{
    DDLOG_CURRENT_METHOD;
    
    BMKPointAnnotation * point = (id)annotation;
    if ([point.title isEqualToString:@"man"]) {
        NSString *AnnotationViewID = @"man";
        //根据指定标识查找一个可被复用的标注View，一般在delegate中使用，用此函数来代替新申请一个View
        MyPaoPaoView *annotationView = (MyPaoPaoView *)[view dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
        if (annotationView == nil) {
            annotationView = [[MyPaoPaoView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
            //        ((MyPaoPaoView *)annotationView).pinColor = BMKPinAnnotationColorRed;
            ((MyPaoPaoView *)annotationView).animatesDrop = YES;
            
            annotationView.delegate = self;
            
        }
        
        if (dataArray.count) {
            [annotationView.headIV sd_setImageWithURL:[NSURL URLWithString:dataArray[num][@"EmplAvator"]] placeholderImage:nil];
            annotationView.titleLB.text = dataArray[num][@"EmplName"];
            annotationView.subTitleLB.text = dataArray[num][@"LevelName"];
            annotationView.backgroundColor = mClearColor;
            annotationView.tag = 88000+num;
            num++;
        }
        
        annotationView.centerOffset = CGPointMake(0, -(annotationView.frame.size.height * 0.5));
        annotationView.annotation = annotation;
        annotationView.canShowCallout = NO;
        annotationView.draggable = NO;
        [self performSelector:@selector(changeCenter) withObject:self afterDelay:1.5f];
        [mapView setCenterCoordinate:annotation.coordinate animated:YES];
        
        return annotationView;
        
    }else{
        
        NSString *AnnotationViewID = @"point";
        //根据指定标识查找一个可被复用的标注View，一般在delegate中使用，用此函数来代替新申请一个View
        BMKPinAnnotationView * annotationView = (BMKPinAnnotationView *)[view dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
        if (annotationView == nil) {
            annotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
            ((BMKPinAnnotationView *)annotationView).pinColor = BMKPinAnnotationColorRed;
            ((BMKPinAnnotationView *)annotationView).animatesDrop = YES;
        }
        
        annotationView.centerOffset = CGPointMake(0, -(annotationView.frame.size.height * 0.5));
        annotationView.annotation = annotation;
        annotationView.canShowCallout = YES;
        annotationView.draggable = NO;
        [self performSelector:@selector(changeCenter) withObject:self afterDelay:1.5f];
        [mapView setCenterCoordinate:annotation.coordinate animated:YES];
        
        return annotationView;
        
    }
    
    
    
    
    
    
}


#pragma mark - 点击气泡跳转页面
- (void)myPaoPaoViewClick:(UITapGestureRecognizer *)tap{
    CameraManDetailViewController * cameraMan = [[CameraManDetailViewController alloc] init];
    cameraMan.cameraManID = dataArray[tap.view.tag - 88000][@"EmplID"];
    //        cameraMan.type = _type;
    if ([dataArray[tap.view.tag - 88000][@"IsAuthen"] intValue]) {
        cameraMan.isRenZheng = YES;
    }else{
        cameraMan.isRenZheng = NO;
    }
    cameraMan.distance = dataArray[tap.view.tag - 88000][@"Range"];
    [self.navigationController pushViewController:cameraMan animated:YES];

}


-(void)changeCenter
{
    CLLocationCoordinate2D cooreinate;
    cooreinate.latitude = latitude;
    cooreinate.longitude = longitude;
    [mapView setCenterCoordinate:cooreinate animated:YES];
    
}

#pragma mark
#pragma mark 选择地址
-(void)chooseAddress
{
    ChooseAddressViewController * chooseVC = [[ChooseAddressViewController alloc] init];
    chooseVC.delegate = self;
    [self.navigationController pushViewController: chooseVC animated:YES];
}


#pragma mark
#pragma mark ChooseAddressViewController Delegate
-(void)chooseBMKPoiInfoFromBaiDuMap:(BMKPoiInfo *)poi
{
    if (poi == nil){
        if ([addressLB.text isEqualToString:@"请选择地址"]){
            //发起反向地理编码检索
            CLLocationCoordinate2D coordinate;
            coordinate.longitude = longitude;
            coordinate.latitude = latitude;
            BMKReverseGeoCodeOption *reverseGeoCodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
            reverseGeoCodeSearchOption.reverseGeoPoint = coordinate;
            BOOL flag = [searcher reverseGeoCode:reverseGeoCodeSearchOption];
            if(flag)
            {
                NSLog(@"反geo检索发送成功");
            }
            else
            {
                NSLog(@"反geo检索发送失败");
            }
        }
    }else{
        //        mapView.showsUserLocation =NO;
        num = 0;
        [dataArray removeAllObjects];
        latitude = poi.pt.latitude;
        longitude =poi.pt.longitude;

        NSString *str = [NSString stringWithFormat:@"拍摄地点:%@",poi.name];
        addressLB.text = str;
        
        mapView.delegate = self;
        
        NSArray* array = [NSArray arrayWithArray:mapView.annotations];
        [mapView removeAnnotations:array];
        
        BMKPointAnnotation * item = [[BMKPointAnnotation alloc]init];
        item.coordinate = poi.pt;
        item.title = poi.name;
        [mapView addAnnotation:item];
        
        NSDictionary * dict = @{@"Lat": [NSString stringWithFormat:@"%f",poi.pt.latitude],
                                @"Lng": [NSString stringWithFormat:@"%f",poi.pt.longitude]};
        [XDTools showProgress:self.contentView];
        [self getDataWithDict:dict api:API_FREEPAILIST];
        
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
